import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { NzMessageService, UploadChangeParam } from 'ng-zorro-antd';
import ExcelJS from 'exceljs';
import { ExceljsService } from 'src/app/myService/exceljs.service';


@Component({
  selector: 'app-lingliao',
  templateUrl: './lingliao.component.html',
  styleUrls: ['./lingliao.component.scss']
})
export class LingliaoComponent implements OnInit {
  listOfData;
  id;
  infoArr; // 获取料号，名称、单位、现有库存
  isShow = false;
  applyID; // 申請單號
  material_no; // 料号
  name; // 名称
  unit; // 单位
  union_order//

  stock; // 现有库存
  applyType = '領用單'; // 单据类型
  charge_department; // 费用charge部门
  applicant; // 申请人
  quatity; // 数量
  remark; // 备注
  checker; // 申请状态
  shenpiPerson; // 默认审批人
  shenpiRemark; // 审批人职位（部门主管）
  addchecker = false; // 是否审批
  userdata; // 员工名单

  editCache = {};
  isVisible = false;
  chargeArr = [];
  rowData: any = [];

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    private msg: NzMessageService,
    public excel: ExceljsService,
  ) { }

  ngOnInit(): void {
    this.queryinfo();
    this.queryCharge();
    console.log(this.storage.getStorageData('user'))
    // location.reload();
  }

  // 获取料号，名称、单位、现有库存
  queryinfo() {
    console.log(this.storage.getStorageData('user').job_no);

    this.axios.axiosPost('QueryBaseMaterial', { job_no: this.storage.getStorageData('user').job_no })
      .then((data) => {
        if (data) {
          // console.log(data);
          this.infoArr = data['order'];
          console.log(this.infoArr);
        }
      })
      .catch((err) => {
        console.log(err);
      })
    // 申请领料
    this.axios.axiosPost('QueryMaterialApply', { job_no: this.storage.getStorageData('user').job_no })
      .then((data) => {
        if (data) {
          console.log(data);
          this.listOfData = data['order'];
          // 排序
          this.listOfData.sort((a, b) => {
            return a.applyID < b.applyID ? 1 : -1;
          })
          for (let i = 0; i < this.listOfData.length; i++) {
            this.editCache[i] = { edit: true, isdel: true, data: this.listOfData[i] };
          }
          console.log(this.editCache);
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  // 获取charge部门
  queryCharge() {
    this.axios.axiosPost('QueryChargeDeptInfo')
      .then((data) => {
        if (data) {
          // console.log(data);
          this.chargeArr = data['order'];
          console.log(this.chargeArr);
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  // 新增
  showinput() {
    this.isShow = true;
    this.applyID = '';
    this.material_no = '';
    this.name = '';
    this.unit = '';
    this.union_order = "";
    this.stock = '';
    this.charge_department = '';
    this.applicant = '';
    this.quatity = '';
    this.remark = '';
  }
  // 输入料号自动带出名称、单位、现有库存
  check() {
    // debugger
    const material = this.infoArr.filter(res => res['material_no'] === this.material_no);
    console.log(material)
    if (material.length > 0) {
      this.name = material[0].name;
      this.unit = material[0].unit;
      this.stock = material[0].stock;
      this.applicant = this.storage.getStorageData('user').name;
    } else {
      this.name = undefined;
      this.unit = undefined;
      this.stock = undefined;
    }
  };

  downloadTemplate() {
     let head = ['串聯單號', '料號', '名稱', '單位', '現有庫存', '單據類型', '費用Charge部門', '申請人', '數量', '備註'];
     let reportData = {
       title: '領料申請',
       data: null,
       headers: head
     };
     this.excel.exportMaterialApplyTemplate(reportData);
  }

  customRequest = (item: any) => {
     
    // 1.获取Excel数据
    const file = item.file;
    const uploadData = [];
    const reader = new FileReader();
    let materialNoDict = {}; // 存储已经出现过的material_no
  
    reader.onload = (e: any) => {
      const fileContent = e.target.result;
  
      const workbook = new ExcelJS.Workbook();
      workbook.xlsx.load(fileContent).then(() => {
        const worksheet = workbook.worksheets[0];
  
        worksheet.eachRow((row, rowNum) => {
          // 第一行的列名不需要获取
          if (rowNum > 1) {
            this.rowData = {
              union_order: row.getCell(1).value,
              material_no: row.getCell(2).value,
              name: row.getCell(3).value,
              unit: row.getCell(4).value,
              stock: row.getCell(5).value,
              applyType: row.getCell(6).value,
              charge_department: row.getCell(7).value,
              applicant: row.getCell(8).value,
              quatity: row.getCell(9).value,
              remark: row.getCell(10).value,
            };
            // 以下是对获取到的数据进行检验

            // name一般包括字符串和数字，但是ExcelJS默认包装成一个richText对象并拆分成字符串和数字两部分，需要重新组合
            if (typeof (this.rowData.name) != 'string') {// richText报的错不用管，由于是richText是this.rowData.name赋值后才有的属性，系统识别不出来
               this.rowData.name = this.rowData.name.richText?.map((item) => item.text).join('');
            }
            
            // remark若没有值则获取到的是null，需要转化为空字符串
            if (this.rowData.remark == null) this.rowData.remark = '';

            let location = `第${rowNum - 1}行的`;
            // 检查material、stock、name、unit、charge_department、applicant、quantity
            const material = this.infoArr.filter(res => res['material_no'] === this.rowData.material_no);
            if (material.length > 0) {
              if (this.rowData.stock != null && this.rowData.stock != 0) {
                if (this.rowData.material_no != null && this.rowData.name != null && this.rowData.unit != null && this.rowData.charge_department != null && this.rowData.applicant != null && this.rowData.quatity != null) {
                  if (typeof (this.rowData.quatity) == "number" && this.rowData.quatity > 0) {
                     uploadData.push(this.rowData);
                  } else {// alert用于前端展示， throw new Error用于中断整个函数执行
                    alert(location + '數量类型不为正数！');
                    throw new Error(location + '數量类型不为正数！');
                  }
                } else {
                  alert(location + '料號/費用Charge部門/申請人/數量/串聯工單 不能為空！');
                  throw new Error(location + '料號/費用Charge部門/申請人/數量/串聯工單 不能為空！');
                }
              } else {
                alert(location + '現有庫存不能為0！');
                throw new Error(location + '現有庫存不能為0！');
              }
            } else {
              alert(location + '料號不存在！');
              throw new Error(location + '料號不存在！');
            }

            // 检查material_no是否重复
            if (materialNoDict.hasOwnProperty(this.rowData.material_no)) {
              const duplicatedRowNum = materialNoDict[this.rowData.material_no];
              alert(`第${duplicatedRowNum}行和第${rowNum-1}行的料號重复！`);
              throw new Error(`第${duplicatedRowNum}行和第${rowNum}行的material_no重复！`);
            }else {
              // 将该material_no添加到字典中
              materialNoDict[this.rowData.material_no] = rowNum-1;
            }
          }
        });

        console.log(uploadData);
     
        // 2.请求Api将数据导入数据库
        if (uploadData.length > 0) {
          this.axios.axiosPost('BatchAddMaterialApply',uploadData)
          .then((data) => {
            console.log(data)
            if (data['result'] === 'ok') {
              console.log(data);
              this.msg.success(`${file.name} file uploaded successfully`);

              this.queryinfo();

            } else {
              alert(data["description"])
            }
          })
          .catch((err) => {
            console.log(err)
          })
        } 
        
      }).catch((error: any) => {
        console.error(error);
      });
    };
  
    reader.readAsArrayBuffer(file);
  }

  // 确认新增
  confirmAdd() {
    // debugger
    const material = this.infoArr.filter(res => res['material_no'] === this.material_no);
    console.log(material)
    if (material.length > 0) {
      if (this.stock !== '' && this.stock != 0) {
        if (this.material_no !== '' && this.name !== '' && this.unit !== '' && this.charge_department !== '' && this.applicant !== '' && this.quatity !== '') {
          if (typeof (this.quatity) == "number" && this.quatity > 0) {
            this.axios.axiosPost('AddMaterialApply', {
              material_no: this.material_no,
              name: this.name,
              unit: this.unit,
              stock: this.stock,
              union_order: this.union_order,
              charge_department: this.charge_department,
              applicant: this.applicant,
              quatity: this.quatity,
              remark: this.remark,
              applyType: this.applyType
            })
              .then((data) => {
                console.log(data)
                if (data['result'] === 'ok') {
                  console.log(data);
                  this.queryinfo();
                  this.isShow = false;

                } else {
                  alert(data["description"])
                }
              })
              .catch((err) => {
                console.log(err)
              })
            // this.isShow = false;
          } else {
            // console.log(this.quatity, typeof (this.quatity));

            alert("数据类型不为正数")
          }
        } else {
          alert('料號/費用Charge部門/申請人/數量/串聯工單 不能為空');
        }
      } else {
        alert('現有庫存不能為0')
      }
    } else {
      alert('料號不存在')
    }
  }
  // 取消新增
  cancelAdd() {
    this.isShow = false;
  }

  // 修改信息
  startEdit(key: number): void {
    // debugger
    console.log(key)
    console.log(this.editCache[key])
    if (this.editCache[key]['data'].checker == "" || this.editCache[key]['data'].status == 'false') {
      this.editCache[key].isdel = false;
      this.editCache[key].edit = false;
      this.id = this.editCache[key]['data'].id;
    } else {
      alert("訂單已審批，不可操作")
    }

  }
  // 保存修改
  saveEdit(key: number): void {
    // if (this.editCache[key]['data'].union_order !== "") {
    if (typeof (this.editCache[key]['data'].quatity - 1 + 1) == "number") {
      if (this.editCache[key]['data'].quatity > 0) {
        this.editCache[key].isdel = true;
        this.editCache[key].edit = true;
        this.axios.axiosPost('UpdateMaterialApply', {
          id: this.id,
          union_order: this.editCache[key]['data'].union_order,
          charge_department: this.editCache[key]['data'].charge_department,
          applicant: this.editCache[key]['data'].applicant,
          quatity: this.editCache[key]['data'].quatity,
          status: "",
          remark: this.editCache[key]['data'].remark,
        })
          .then((data) => {
            // console.log(data)

            if (data['result'] === 'ok') {
              this.queryinfo();
            } else {
              alert(data["description"])
              this.queryinfo();

            }
          })
          .catch((err) => {
            console.log(err);
          })

      } else {
        alert("数量不能小于等于0")
      }
    } else {
      console.log(this.editCache[key]['data'].quatity, typeof (this.editCache[key]['data'].quatity));

      alert("数据类型不属于数字")
    }
    // } else {
    //   alert("未輸入串聯工單")
    // }
    // debugger

  }
  // 撤销修改
  cancelEdit(key: number): void {
    this.queryinfo();
  }

  // 删除
  showModal(item): void {
    // debugger
    console.log(item.status)
    if (item.status == "false" || item.status == "") {
      this.isVisible = true;
      this.id = item.id;
    } else {
      alert("訂單已審批，不可操作")
    }
  }
  handleOk() {
    this.isVisible = false;
    // debugger
    this.axios.axiosPost('DeleteMaterialApply', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.queryinfo();
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }


  // 審批
  addChecker(item) {
    this.addchecker = true;
    // 获取name
    this.shenpiPerson = this.storage.getStorageData('user').name;
    this.shenpiRemark = this.storage.getStorageData('user').remark;
    this.id = item.id
    // console.log(this.storage.getStorageData('user').job_no)
    console.log(this.shenpiRemark)
  }
  CheckOk() {
    // debugger
    if (this.shenpiRemark.indexOf('部門主管') !== -1) {
      this.axios.axiosPost('UpdateMaterialApply', { id: this.id, checker: this.shenpiPerson, status: true })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            console.log(data);
            this.queryinfo();
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      alert('職位不是部門主管，不能進行審批');
    }
    this.addchecker = false;
  }
  CancelCheck2() {
    this.addchecker = false;

  }
  CancelCheck() {
    this.axios.axiosPost('UpdateMaterialApply', { id: this.id, checker: this.shenpiPerson, status: false })
      .then((data) => {
        if (data['result'] === 'ok') {
          console.log(data);
          this.queryinfo();
        }
      })
      .catch((err) => {
        console.log(err)
      })
    this.addchecker = false;
  }

}
